using AutoMapper;
using BackData;
using Domain.生产订单;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Order;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Hanldler.Order
{
    /// <summary>
    /// 创建订单命令处理器
    /// </summary>
    public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, APIResult<int>>
    {
        private readonly IMapper _mapper;
        private readonly IRepository<OrderModel> _orderRep;
        private readonly ILogger<CreateOrderHandler> _logger;

        public CreateOrderHandler(
            IMapper mapper,
            IRepository<OrderModel> orderRep,
            ILogger<CreateOrderHandler> logger)
        {
            _mapper = mapper;
            _orderRep = orderRep;
            _logger = logger;
        }

        public async Task<APIResult<int>> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 数据验证
                if (request.Number <= 0)
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.Fail,
                        Message = "订单数量必须大于0",
                        Result = 0
                    };
                }

                if (request.Itemcode <= 0)
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.Fail,
                        Message = "成品编号无效",
                        Result = 0
                    };
                }

                // 映射并创建订单
                var order = _mapper.Map<OrderModel>(request);
                order.Id = YitIdHelper.NextId();
                
                // 设置默认值
                order.Ordertime = request.Ordertime ?? DateTime.Now;
                order.Orderstatus = request.Orderstatus ?? 0; // 默认为待排程

                var result = await _orderRep.AddAsync(order);

                if (result > 0)
                {
                    _logger.LogInformation($"订单创建成功: 成品编号={request.Itemcode}, 数量={request.Number}");
                    return new APIResult<int>
                    {
                        Code = StateCode.OK,
                        Message = "订单创建成功",
                        Result = result
                    };
                }
                else
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.Fail,
                        Message = "订单创建失败",
                        Result = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "订单创建失败");
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = $"订单创建失败: {ex.Message}",
                    Result = 0
                };
            }
        }
    }
}
